package com.space.school.dao.impl;

import com.space.school.dao.OrderDao;
import com.space.school.domain.Category;
import com.space.school.domain.Order;
import com.space.school.domain.OrderMaster;
import com.space.school.domain.ProductInfo;
import com.space.school.utils.SpaceJDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

public class OrderDaoImpl implements OrderDao {
    //    获取数据库并连接
    private JdbcTemplate jdbcTemplate=new JdbcTemplate(SpaceJDBCUtils.getDs());
    @Override
    public List<ProductInfo> productList() {
        String sql="select * from product_info where product_status=0  ";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<ProductInfo>(ProductInfo.class));
    }

    @Override
    public void insert(Order order) {
        // 更新语句
        String sql="insert into order_detail (detail_id,order_id,product_id,product_num,create_time) values(?,?,?,?,?)";
        jdbcTemplate.update(sql,order.getDetail_id(),order.getOrder_id(),order.getProduct_id(),order.getProduct_num(),new Date());
    }
    @Transactional
//    事物
//    事物回滚
    @Override
    public void delete(String order_id) {
        String sql="delete from order_detail where order_id=?";
        jdbcTemplate.update(sql,order_id);
    }

    @Override
    public List<OrderMaster> totalList(String order_id) {
        String sql="select sum(a.order_total)as order_total,sum(a.order_amount) as order_amount from (select sum(a.product_num) as order_total ,sum(a.product_num)*b.product_price as order_amount from order_detail a left join product_info b on a.product_id=b.product_id  where a.order_id=? group by a.product_id)a";

        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<OrderMaster>(OrderMaster.class),order_id);
    }

    @Override
    public void insert(OrderMaster orderMaster) {
        // 更新语句
        String sql="insert into order_master (order_id,buyer_name,buyer_phone,buyer_address,buyer_openid,order_amount,order_total,order_status,pay_status,create_time) values(?,?,?,?,?,?,?,?,?,?)";
        jdbcTemplate.update(sql,orderMaster.getOrderId(),orderMaster.getBuyer_name(),orderMaster.getBuyer_phone(),orderMaster.getBuyer_address(),orderMaster.getBuyer_openid(),orderMaster.getOrder_amount(),orderMaster.getOrder_total(),orderMaster.getOrder_status(),orderMaster.getPay_status(),new Date());
    }
}
